//
//  BankCardListViewModel.m
//  GLGW_Shoping
//
//  Created by whx on 2018/12/5.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "BankCardListViewModel.h"
#import "NoDataFootTableViewHeaderFooterView.h"
#import "BankCardDetailTableViewCell.h"
#import "BankCardlistHeaderView.h"
#import "BankCardListBottomView.h"
#import "NoCardsDataView.h"
#import "BankCardListUseBttomView.h"
#import "BankCardModel.h"
#import "LoginModel.h"

@interface BankCardListViewModel ()<UITableViewDelegate, UITableViewDataSource>
{
    UITableView *selfTableView;
    UIView *view;
    NSInteger status;            // 记录选状态
    UIButton *editBtn;
}
@property (nonatomic, strong) NoCardsDataView *dataView;
@property (nonatomic ,strong) BankCardListUseBttomView *bottomView;//底部视图

@end

@implementation BankCardListViewModel

- (instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView
{
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        view = superView;
        tableView.height -= kHeightProportion_In_iPhoneTriploid(44);
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.sectionFooterHeight = 0.0;
        tableView.sectionHeaderHeight = 0.0;
        tableView.mj_header.hidden = YES;
        tableView.mj_footer.hidden = YES;
        [tableView registerClass:[NoDataFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"NoDataFootTableViewHeaderFooterView"];
        [tableView registerClass:[BankCardlistHeaderView class] forHeaderFooterViewReuseIdentifier:@"BankCardlistHeaderView"];
        [superView addSubview:tableView];
        selfTableView = tableView;
        
        BankCardListBottomView *bottomView = [[BankCardListBottomView alloc] initWithInSuperView:superView];
        kWeakSelf(self);
        bottomView.BlockAddCard = ^(GLGWButton * _Nullable btn) {
            [weakself addBankCard:btn];
        };
        [self showNoDataView];
    }
    return self;
}

- (void)showNoDataView
{
    if (self.BlockNoData) {
        self.BlockNoData();
    }
    [self showNoDataImageView:self.dataView];
}

- (void)removeNodata
{
    [view bringSubviewToFront:selfTableView];
    [view sendSubviewToBack:self.dataView];
    [self removeNoDataImage];
}

- (void)addBankCard:(GLGWButton *)seder
{
    if (self.BlockAddCard) {
        self.BlockAddCard(seder);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeightProportion_In_iPhoneTriploid(19);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    BankCardlistHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"BankCardlistHeaderView"];
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NoDataFootTableViewHeaderFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"NoDataFootTableViewHeaderFooterView"];
    return footer;
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.model.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kHeightProportion_In_iPhoneTriploid(120);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BankCardDetailTableViewCell *detailCell = [BankCardDetailTableViewCell cellWithTableView:tableView];
    if (self.model.data.count > 0) {
        BankCardDetailModel *deModel = self.model.data[indexPath.row];
        detailCell.model = deModel;        
    }
    return detailCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing) {
        
    } else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        if (self.type == ChooseCardType_Return) {
            if (self.BlockChooseBank) {
                self.BlockChooseBank([NSDictionary dictionary]);
            }
        }
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.editing) {
    }
    //        DLog(@"取消跳转");
}

#pragma mark -编辑
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete|UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
    //    if (editingStyle == UITableViewCellEditingStyleDelete) {
    //        [self.dataArray removeObjectAtIndex: indexPath.row];
    //        [self.tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath]
    //                              withRowAnimation:UITableViewRowAnimationFade];
    //        [self.tableView reloadData];
    
    //    }
}

- (void)setEdit:(UIButton *)sender
{
    editBtn = sender;
    sender.selected = !sender.selected;
    if (sender.selected) {
        //点击编辑的时候清空删除数组
        [sender setTitle:@"完成" forState:UIControlStateNormal];
        sender.tintColor = [UIColor whiteColor];
        [sender setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:UIControlStateSelected];
        [selfTableView setEditing:YES animated:YES];
        
        if (_bottomView.seleAll.selected) { // 改变文字
            _bottomView.seleAll.selected = !_bottomView.seleAll.selected;
            [_bottomView.seleAll setTitle:@"全选" forState:UIControlStateNormal];
        }
        [self.bottomView showView];
        
    } else {
        [self noEdit:sender];
    }
}

- (void)noEdit:(UIButton *)sender
{
    [sender setTitle:@"编辑" forState:UIControlStateNormal];
    [selfTableView setEditing:NO animated:YES];
    [self.bottomView dismissView];
}

- (void)seletAll:(GLGWButton *)btn
{
    btn.selected = !btn.selected;
    
    if (btn.selected) {
        for (int i = 0; i< _model.data.count; i++) { // 全选实现方法
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            [selfTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
        }
        [btn setTitle:@"取消" forState:UIControlStateNormal];
    } else { // 取消选中
        NSArray *indexArr = [selfTableView indexPathsForSelectedRows];
        for (int i = 0; i < indexArr.count; i++) {
            NSIndexPath *indexPath = indexArr[i];
            [selfTableView deselectRowAtIndexPath:indexPath animated:NO];
        }
        [btn setTitle:@"全选" forState:UIControlStateNormal];
    }
}

// 删除数据方法
- (void)deleteData:(BOOL)isStart
{
    if (self.model.data.count <= 0) return;
    if (isStart == YES) { //停用
        status = 1;
    } else {  // 启用
        status = 2;
    }
    [self requestStartBankCardList];
}

- (BankCardListUseBttomView *)bottomView
{
    if (!_bottomView) {
        _bottomView = [[BankCardListUseBttomView alloc] initWithInSuperView:view];
        [_bottomView.seleAll addTarget:self action:@selector(seletAll:) forControlEvents:UIControlEventTouchUpInside];
        kWeakSelf(self);
        _bottomView.BlockAllDelete = ^(GLGWButton * _Nullable deleteBtn) {
            [weakself deleteData:YES];
        };
        _bottomView.BlockStart = ^(GLGWButton * _Nullable startBtn) {
            [weakself deleteData:NO];
        };
    }
    return _bottomView;
}

- (BankCardModel *)model
{
    if (!_model) {
        _model = [[BankCardModel alloc] init];
    }
    return _model;
}

- (NoCardsDataView *)dataView
{
    if (!_dataView) {
        _dataView = [[NoCardsDataView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    }
    return _dataView;
}

- (void)setRefreshType:(AddOrEditType)refreshType
{
    _refreshType = refreshType;
    if (refreshType == AddOrEditType_Defat) { // 刷新
        [self requestBankCardList];
    } else if (refreshType == AddOrEditType_Add) {
        [self removeNodata];
        NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
        [selfTableView insertRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationFade];
    } else if (refreshType == AddOrEditType_Edit) {// 听说二期要加编辑
    }
}


#pragma mark - 请求接口
- (void)requestBankCardList
{
    if (self.userInforData.length == 0) return;
    LoginModel *modles = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
    NSDictionary *params = @{@"userId" : koString(modles.data.userId)};
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kBankCardInfor] lodingView:nil lodingTextString:@"" isLoding:YES parameters:params success:^(id  _Nullable response) {
        self.model = [BankCardModel yy_modelWithJSON:response];
        if ((int)self.model.code == 0) {
            [self removeNodata];
            [self->selfTableView reloadData];
        }
    } failure:^(NSError * _Nullable error) {
        DLog(@"银行卡列表信息:%@",error);
    }];
}

// 启用/停用接口
- (void)requestStartBankCardList{
    if (self.userInforData.length == 0) return;
    LoginModel *modles = [NSKeyedUnarchiver unarchiveObjectWithData:self.userInforData];
    NSArray *arr = [selfTableView indexPathsForSelectedRows];
    if (arr.count <= 0) return; // 这里或许可以给一个提示
    NSMutableArray *cardIDArr = [NSMutableArray array];
    for (int i = 0; i < arr.count; i ++) {
        NSIndexPath *index = arr[i];
        BankCardDetailModel *deModel = self.model.data[index.row];
        NSString *cardID = deModel.ID;
        [cardIDArr addObject:cardID];
    }

    NSDictionary *params = @{
                             @"ids" : cardIDArr,
                             @"userId" : koString(modles.data.userId),
                             @"status" : @(status)
                             };
    if (self.userInforData.length == 0) return;
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kBankCardStatusSwitch] lodingView:nil lodingTextString:@"" isLoding:YES parameters:params success:^(id  _Nullable response) {
        BaseModel *baseModel = [BaseModel yy_modelWithJSON:response];
        if ((int)baseModel.code == 0) {
            [self refreshData];
        } else {
            DLog(@"%@",baseModel.message);
        }
    } failure:^(NSError * _Nullable error) {
        DLog(@"银行卡列表信息:%@",error);
    }];
}

- (void)refreshData
{
    NSArray *seleArr = [selfTableView indexPathsForSelectedRows];
    for (int i = 0; i < seleArr.count; i ++) {
        NSIndexPath *index = seleArr[i];
        BankCardDetailModel *deModel = self.model.data[index.row];
        deModel.status = status;
    }
    [selfTableView reloadRowsAtIndexPaths:seleArr withRowAnimation:UITableViewRowAnimationAutomatic];
    [self noEdit:editBtn];
    editBtn.selected = NO;
}

@end
